package com.xh.common;

import java.beans.BeanInfo;
import java.beans.Introspector; 
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import net.sf.json.JSONObject;

/**
 * @Description: 对象工具类
 * @author:      ZhangHua
 * @date:        2015-07-18
 */

public class ObjectUtils {
	
	/**
	 * 将list转换成只含javaBean的list
	 * @param <T>
	 * @param <T>
	 * @param paramList
	 * @return
	 */
	public static <T> List<T> toListForJavaBean(List<T> paramList,Class<T> type)
	{
		List<T> list = new ArrayList<T>();
		
		for (int i = 0; i < paramList.size(); i++) 
		{
			Map map = (Map)paramList.get(i);
			Map<String, Object> itemMap = new HashMap<String, Object>();
			
			//遍历map
			Iterator it = map.entrySet().iterator();
			
			while (it.hasNext()) 
			{
				Map.Entry entry = (Map.Entry)it.next();
				String value = entry.getValue() == null ? "" : entry.getValue().toString();
				itemMap.put(entry.getKey().toString(), value);
			}
			
			T tObj = mapToJavaBean(itemMap,type);
			list.add(tObj);
		}  

		return list;
	}
	
	 /** 
     * 将一个 Map 对象转化为一个 JavaBean 
	 * @param <T>
     * @param type 要转化的类型 
     * @param map 包含属性值的 map 
     * @return 转化出来的 JavaBean 对象 
     */ 
    public static <T> T mapToJavaBean(Map<String,Object> map,Class<T> type) {
    	try {
	        BeanInfo beanInfo = Introspector.getBeanInfo(type); // 获取类属性 
	        Object obj = type.newInstance(); // 创建 JavaBean 对象 
	
	        // 给 JavaBean 对象的属性赋值 
	        PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors(); 
	        
	        for (int i = 0; i< propertyDescriptors.length; i++) { 
	            PropertyDescriptor descriptor = propertyDescriptors[i]; 
	            String propertyName = descriptor.getName();
	            propertyName = propertyName.toLowerCase();
	            String propertyValue = "";
	            
	            if (map.containsKey(propertyName)) {    
	            	try {
		                Object value = map.get(propertyName); 
		                propertyValue = value.toString();
		                value = getFiledValue(obj,propertyName,value);
		
		                Object[] args = new Object[1]; 
		                args[0] = value; 
		
		                descriptor.getWriteMethod().invoke(obj, args); 
	            	}
	            	catch (Exception exc) {
	            		System.out.println("Error 对象解析异常: [name:" + propertyName + " value: " + propertyValue + "]");
	            	}
	            } 
	        } 
	        
	        return (T) obj; 
    	}
    	catch (Exception exc) {
    		exc.printStackTrace();
    	}
    	
    	return null;
    }
    
    /** 
     * 获取对象属性相应类型的值
     * @param obj
     * @param propertyName 属性名
     * @param Value 属性值
     * */  
    private static Object getFiledValue(Object obj,String propertyName, Object value){  
    	 Field[] fields = obj.getClass().getDeclaredFields();  
     
    	 try {
		     for (int i = 0; i < fields.length; i++) {  
		    	 String fieldName = fields[i].getName();
		    	 
		    	 if (fieldName.equalsIgnoreCase(propertyName)) {
		    		 String valueStr = value.toString();
		    		 String fieldType = fields[i].getType().toString();
		    		 fieldType = fieldType.toLowerCase();
		    		 
		    		 if (fieldType.indexOf("java.util.list") >= 0) {
		    			 return value;
		    		 }
		    		 
		    		 if (fieldType.indexOf("int") >= 0) {
		    			 value = Integer.valueOf(valueStr);
		    		 }
		    		 
		    		 if (fieldType.indexOf("java.lang.double") >= 0) {
		    			 value = Double.valueOf(valueStr);
		    		 }
		    		
		    		 /*if (fieldType.indexOf("java.util.date") >= 0) {
		    			 value = DateUtils.stringToDate(valueStr);
		    		 }*/
		    		
		    		//有做修改
		    		 if (fieldType.indexOf("java.lang.long") >= 0) {
		    			 value = Long.valueOf(valueStr);
		    		 }
		    		 
		    		
		    		 
		    		 return value;
		    	 }
		     }
    	 }
    	 catch (Exception e) {
     		System.out.println("Error 获取对象属性相应类型值异常: [name:" + propertyName + " value: " + value.toString() + "]");
     	 }
	     
	     return value;  
    }  
    
    /**  
     * 把json对象串转换成map对象且key名全为小写字符  
     * @param jsonStr  
     * @return Map  
     */  
     public static Map<String,Object> jsonToMapByLower(String jsonStr) {
		JSONObject jsonObject = JSONObject.fromObject(jsonStr);

		Map<String, Object> map = new HashMap<String, Object>();

		for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
			String key = (String) iter.next();
			String lowerKey = key.toLowerCase();
			map.put(lowerKey, jsonObject.get(key));
		}

		return map;
     }    
     
    /** 
     * 将一个 JavaBean 对象转化为一个 Map 
	 * @param obj
     * @return 转化出来的 map 对象 
     */ 
    public static Map<String,Object> javaBeanToMap(Object obj) {  
        if (obj == null) {  
            return null;  
        } 
        
        Map<String, Object> map = new HashMap<String, Object>(); 
        
        try {  
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());  
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
            
            for (PropertyDescriptor property : propertyDescriptors) {  
                String key = property.getName();  
  
                // 过滤class属性  
                if (!key.equals("class")) {  
                    // 得到property对应的getter方法  
                    Method getter = property.getReadMethod();  
                    Object value = getter.invoke(obj);  
  
                    map.put(key, value);  
                }  
  
            }  
        } catch (Exception e) {  
            System.out.println("javaBeanToMap Error " + e);  
        }  
  
        return map;  
    }  
	
    /**
     * json字符串 to JavaBean
     * @param jsonStr json字符串
     * @param type 要转化的类型
     * @return
     */
    @SuppressWarnings("unchecked")
	public static <T> T jsonToJavaBean(String jsonStr,Class<T> type) {
		try {
			Map<String,Object> map = jsonToMapByLower(jsonStr);
			return (T) mapToJavaBean(map,type);
		} catch (Exception e) {
			System.out.println("jsonToJavaBean Error " + e);
		}
   
    	return null;
    }
    
    /**  
     * 获取主键唯一标识guid  
     * @return  
     */  
     public static String getGUID() {
    	 UUID uuid = UUID.randomUUID();
    	 String guid = uuid.toString();
    			 
    	 guid = guid.replaceAll("-", "");
    	 return guid;  
     }   
}
